package com.shwread.android.qysw.activity.healthy;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.shwread.android.qysw.step.api.MyAsynctask;
import com.shwread.android.qysw.step.dto.HMUserInfo;
import com.shwread.android.qysw.step.dto.HMUserInfoDto;
import com.shwread.android.qysw.step.model.UserHealthyModel;
import com.shwread.android.qysw.step.view.PickerView;
import com.shwread.android.qysw.tools.TimeHelper;
import com.shwread.android.qysw10000227.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.util.Calendar;
import java.util.HashMap;

import butterknife.ButterKnife;
import butterknife.InjectView;
import logic.constants.AppConfig;
import logic.constants.Const;

/**
 * Created by Fantasy on 16/3/27.
 */
public class HealthyMyGoalStepActivity extends Activity {
    public Calendar startCalendar;
    public Calendar endCalendar;
    @InjectView(R.id.back_btn)
    ImageView backBtn;
    @InjectView(R.id.back_text)
    TextView backText;
    @InjectView(R.id.title_text)
    TextView titleText;
    @InjectView(R.id.right_text)
    TextView rightText;
    @InjectView(R.id.right_img)
    ImageView rightImg;
    @InjectView(R.id.start_date)
    TextView startDate;
    @InjectView(R.id.start_date_button)
    LinearLayout startDateButton;
    @InjectView(R.id.end_date)
    TextView endDate;
    @InjectView(R.id.end_date_button)
    LinearLayout endDateButton;
    @InjectView(R.id.every_day_goal_step_text)
    EditText everyDayGoalStepText;
    @InjectView(R.id.every_day_goal_step_button)
    LinearLayout everyDayGoalStepButton;
    @InjectView(R.id.cancle)
    TextView cancle;
    @InjectView(R.id.sure)
    TextView sure;
    @InjectView(R.id.line_view)
    View lineView;
    @InjectView(R.id.item_pv)
    PickerView itemPv;
    @InjectView(R.id.picker_layout)
    RelativeLayout pickerLayout;
    @InjectView(R.id.submit_button)
    RelativeLayout submitButton;
    @InjectView(R.id.submit_text)
    TextView submitText;
    @InjectView(R.id.score_text)
    TextView scoreText;
    HMUserInfo mHmUserInfo;
    private DatePickerDialog startTimeDialog;
    private long startTime = 0;
    private long endTime = 0;
    private int dayCount = 0;
    private DatePickerDialog endTimeDialog;
    private String selectText;
    private String mTargetStart;
    private String mTargetEnd;
    private int mStartMonth;
    private int maxLen=8;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.healthy_my_goal_step_activity);
        ButterKnife.inject(this);
        setView();
        everyDayGoalStepText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
//                Editable editable = everyDayGoalStepText.getText();
//                int len = editable.length();
//                int nowLength = s.toString().length();
//                Selection.setSelection(editable, nowLength);

            }

            @Override
            public void afterTextChanged(Editable s) {
                String step = s.toString().trim();
                if (!TextUtils.isEmpty(step)) {
                    int score = Integer.valueOf(step) / 5000;
                    scoreText.setText("完成每天目标步数可获得" + score + "积分哦!");
                    scoreText.setVisibility(View.VISIBLE);
                } else {
                    scoreText.setVisibility(View.INVISIBLE);
                }
            }
        });
        mHmUserInfo = UserHealthyModel.getInstance().getMyHmUserInfo();
        Log.i("darren", "target:" + mHmUserInfo.getTarget());
        Log.i("darren", "targetNow:" + System.currentTimeMillis());
        Log.i("darren", "targetEnd:" + mHmUserInfo.getTargetEnd());
        if (mHmUserInfo.getTarget() > 0 && System.currentTimeMillis() < mHmUserInfo.getTargetEnd()) {
            startDate.setText(TimeHelper.getDateY_M_D_TimByStamp(mHmUserInfo.getTargetStart()));
            endDate.setText(TimeHelper.getDateY_M_D_TimByStamp(mHmUserInfo.getTargetEnd()));
            everyDayGoalStepText.setText(mHmUserInfo.getTarget() + "");
            submitText.setText("编辑");
            scoreText.setVisibility(View.VISIBLE);
            int score = mHmUserInfo.getTarget() / 5000;
            scoreText.setText("完成每天目标步数可获得" + score + "积分哦!");
            startDateButton.setClickable(false);
            endDateButton.setClickable(false);
            everyDayGoalStepText.setEnabled(false);
            try {
                startTime = TimeHelper.getStartTime(startDate.getText().toString());
                endTime = TimeHelper.getEndTime(endDate.getText().toString());
                startTime = TimeHelper.getStartTime(startDate.getText().toString());
                mTargetStart = startTime + "";
                endTime = TimeHelper.getEndTime(endDate.getText().toString());
                mTargetEnd = endTime + "";
            } catch (ParseException e) {
                e.printStackTrace();
            }
        } else {
            startDateButton.setClickable(true);
            endDateButton.setClickable(true);
            everyDayGoalStepText.setEnabled(true);
            scoreText.setVisibility(View.INVISIBLE);
            submitText.setText("确定");
        }
        Calendar calendar = Calendar.getInstance();
        int mMonth = calendar.get(Calendar.MONTH);
        startTimeDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                startDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                try {
                    startTime = TimeHelper.getStartTime(startDate.getText().toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                mTargetStart = startTime + "";
                Log.i("darren", "start:" + mTargetStart + "");
                Log.i("darren", "current:" + System.currentTimeMillis() + "");
                endTimeDialog.getDatePicker().setMinDate(startTime);
            }
        }, calendar.get(Calendar.YEAR), mMonth, calendar.get(Calendar.DAY_OF_MONTH));
        startTimeDialog.getDatePicker().setMinDate(TimeHelper.getTodayTime());
        endTimeDialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                endDate.setText(year + "-" + (monthOfYear + 1) + "-" + dayOfMonth);
                //endTime = view.getCalendarView().getDate();
                try {
                    endTime = TimeHelper.getEndTime(endDate.getText().toString());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                mTargetEnd = endTime + "";
                Log.i("darren", "end" + endTime + "");
            }
        }, calendar.get(Calendar.YEAR), mMonth, calendar.get(Calendar.DAY_OF_MONTH));

    }


    public void setView() {
        titleText.setText("目标步数");
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        startDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startTimeDialog.show();
            }
        });
        endDateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                endTimeDialog.show();
            }
        });

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (submitText.getText().equals("编辑")) {
                    submitText.setText("完成");
                    startDateButton.setClickable(true);
                    endDateButton.setClickable(true);
                    everyDayGoalStepText.setEnabled(true);
                } else {
                    if (endTime < startTime) {
                        Toast.makeText(HealthyMyGoalStepActivity.this, "结束时间不能小于开始时间", Toast.LENGTH_LONG).show();
                    } else {
                        selectText = everyDayGoalStepText.getText().toString();
                        HashMap<String, String> url = new HashMap<String, String>();
                        url.put("url", "hzlqswserver/health/setTarget");
                        HashMap<String, String> params = new HashMap<String, String>();
                        params.put("userId", UserHealthyModel.getInstance().getMyHmUserInfo().getUserId() + "");
                        params.put("enterpriseId", AppConfig.getEnterpriseId());
                        params.put("target", selectText);
                        params.put("targetStart", mTargetStart);
                        params.put("targetEnd", mTargetEnd);
                        if (TextUtils.isEmpty(selectText) || TextUtils.isEmpty(mTargetStart) || TextUtils.isEmpty(mTargetEnd)) {
                            Toast.makeText(HealthyMyGoalStepActivity.this, "请完善信息", Toast.LENGTH_LONG).show();
                        } else {
                            MyAsynctask myAsynctask = new MyAsynctask(HealthyMyGoalStepActivity.this, new MyAsynctask.RequestListener() {
                                @Override
                                public void requestSuccess(String result) {
                                    Toast.makeText(HealthyMyGoalStepActivity.this, "设置成功", Toast.LENGTH_LONG).show();
                                    getUserInfo();
                                }
                            });
                            myAsynctask.execute(url, params);
                        }
                    }

                }
            }
        });
    }

    public void getUserInfo() {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("phoneNum", Const.phone_number);
        params.put("enterpriseId", AppConfig.getEnterpriseId());
        HashMap<String, String> urlMap = new HashMap<>();
        urlMap.put("url", "/hzlqswserver/health/userInfo");
        MyAsynctask myAsynctask = new MyAsynctask(this, new MyAsynctask.RequestListener() {
            @Override
            public void requestSuccess(String result) {
                Log.i("darren", result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("returnObject");
                    HMUserInfoDto hmUserInfoDto = HMUserInfoDto.parserJson(res);
                    UserHealthyModel.getInstance().setMyHmUserInfo(hmUserInfoDto.getHMUserInfo());
                    finish();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        myAsynctask.execute(urlMap, params);
    }


}
